// pages/component/message/message.js
import routerManager from "../../utils/routerManager.js";
import { emojiName, emojiMap, emojiUrl } from '../../utils/emojiMap'
import TIM from "tim-wx-sdk";
import audio from "./audio";

const app = getApp();
Page({
  /**
   * 组件的初始数据
   */
  data: {
    username: "",
    conversationID: "",
    userId: "",
    messageList: [],
    scrolltoId: "",
    nextReqMessageID: "",
    isCompleted: false,
    refresherTriggered: false,
    inputValue: "",
    formUserId: "",
    myAvatar: "",
    inputFocus: false,
    emojiName: emojiName,
    emojiMap: emojiMap,
    emojiUrl: emojiUrl,
    isEmojiOpen:false,
    emojiShow:false,
    formAvatar:"",
    showFuncBar:true,
    isFuncBarShow:false,
    sendingAudio:false,
    isClicking:false,
    canSend:true,
    startPoint: 0,
  },
  bindPlayVoice(event){
    let src = event.currentTarget.dataset.url;
    audio.playVoice(src);
  },
   // 录音时的手势上划移动距离对应文案变化
   handleTouchMove (e) {
    console.log("touch move")
    if(this.data.isClicking){
      if (this.data.startPoint.clientY - e.touches[e.touches.length - 1].clientY > 100) {
        this.setData({
          canSend:false,
        })
      } else if (this.data.startPoint.clientY - e.touches[e.touches.length - 1].clientY > 20) {
        this.setData({
          canSend:true,
        })
      } else {
        this.setData({
          canSend:true,
        })
      }
    }
  },
  sendAudioMsgEnd(event){
    const RecorderManager = wx.getRecorderManager();
    RecorderManager.stop();
    this.setData({
      isClicking:false
    })
  },
  sendAudioMsg(event){
    console.log("longpress",event.target.id == 'audiobtn');
    if(event.target.id == 'audiobtn'){
      let that = this;
      that.setData({
        isClicking:true,
        startPoint: event.touches[0]
      })
      audio.startRecording();
    }
  },
  bindShowAudio(event){
    this.setData({sendingAudio : !this.data.sendingAudio});
  },
  bindFuncBar(e){
    this.setData({
      isFuncBarShow: true,
      isEmojiOpen: false,
    });
    this.scrollToBottom();
  },
  seeImage(e){
    wx.previewImage({
      current: e.currentTarget.dataset.url, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.url] // 需要预览的图片http链接列表
    })
  },
  sendImage(e){
    let that = this;
    let tim = app.$tim;
    // 小程序端发送图片
    // 1. 选择图片
    wx.chooseImage({
      sourceType: ['album'], // 从相册选择
      count: 1, // 只选一张，目前 SDK 不支持一次发送多张图片
      success: function (res) {
        // 2. 创建消息实例，接口返回的实例可以上屏
        let message = tim.createImageMessage({
          to: that.data.formUserId,
          conversationType: TIM.TYPES.CONV_C2C,
          payload: { file: res },
          onProgress: function(event) { console.log('file uploading:', event) }
        });
        // 3. 发送图片
        let promise = tim.sendMessage(message);
        promise.then(function(imResponse) {
          // 发送成功
          console.log(imResponse);
          let msgs = that.data.messageList.concat([imResponse.data.message]);
          that.setData({
            messageList: msgs,
            isFuncBarShow: false
          });
          that.scrollToBottom();
        }).catch(function(imError) {
          // 发送失败
          console.warn('sendMessage error:', imError);
        });
      }
    })
  },
  closeFuncBar(e){
    this.setData({
      isFuncBarShow: false
    });
  },
  showEmoji(e){
    this.setData({
      isEmojiOpen: true,
      isFuncBarShow: false
    });
    this.scrollToBottom();
  },
  closeEmoji(e){
    this.setData({
      isEmojiOpen: false
    });
  },
  chooseEmoji (event) {
    let that = this;
    let text = event.currentTarget.dataset.item;
    let tim = app.$tim;
    // 1. 创建消息实例，接口返回的实例可以上屏
    let message = tim.createTextMessage({
      to: this.data.formUserId,
      conversationType: TIM.TYPES.CONV_C2C,
      payload: {
        text: text
      }
    });
    let msgs = that.data.messageList.concat([message]);
    console.log("msgs", msgs);
    that.setData({
      messageList: msgs,
      inputValue: ""
    });
    that.scrollToBottom();
    // 2. 发送消息
    let promise = tim.sendMessage(message);
    promise
      .then(function(imResponse) {
        // 发送成功
        console.log(imResponse);
      })
      .catch(function(imError) {
        // 发送失败
        console.warn("sendMessage error:", imError);
      });
    that.setData({
      isEmojiOpen: false
    });
  },
  scrollToBottom() {
    let that = this;
    setTimeout(function() {
      that.setData({
        scrolltoId: "btm"
      });
    }, 100);
  },
  checkBtn(){
    if(this.data.inputValue.length==0){
      this.setData({
        showFuncBar:true
      });
    } else {
      this.setData({
        showFuncBar:false
      });
    }
  },
  bindKeyInput: function(e) {
    this.setData({
      inputValue: e.detail.value
    });
    this.checkBtn();
  },
  focus(e) {
    this.checkBtn();
    this.setData({
      inputFocus: true
    });
  },
  bindblur(e) {
    this.checkBtn();
    this.setData({
      inputFocus: false
    });
  },
  sendMsg(event) {
    let that = this;
    let text = this.data.inputValue;
    let tim = app.$tim;
    // 1. 创建消息实例，接口返回的实例可以上屏
    let message = tim.createTextMessage({
      to: this.data.formUserId,
      conversationType: TIM.TYPES.CONV_C2C,
      // 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
      // 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
      // priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
      payload: {
        text: text
      }
    });
    let msgs = that.data.messageList.concat([message]);
    console.log("msgs", msgs);
    that.setData({
      messageList: msgs,
      inputValue: "",
      isFuncBarShow: false
    });
    that.scrollToBottom();
    // 2. 发送消息
    let promise = tim.sendMessage(message);
    promise
      .then(function(imResponse) {
        // 发送成功
        console.log(imResponse);
      })
      .catch(function(imError) {
        // 发送失败
        console.warn("sendMessage error:", imError);
      });
  },
  onRefresh() {
    console.log("onRefresh");
    let that = this;
    if (that.data.isCompleted) {
      that.setData({
        refresherTriggered: false
      });
      wx.showToast({
        title: "没有更多消息了",
        icon: "none",
        duration: 1500,
        mask: false,
        complete: () => {}
      });
      return;
    }
    // 下拉查看更多消息
    let promise = app.$tim.getMessageList({
      conversationID: that.data.conversationID,
      nextReqMessageID: that.data.nextReqMessageID,
      count: 15
    });
    promise.then(function(imResponse) {
      const messageList = imResponse.data.messageList; // 消息列表。
      const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
      const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
      let msgs = messageList.concat(that.data.messageList);
      that.setData({
        messageList: msgs,
        nextReqMessageID: nextReqMessageID,
        isCompleted: isCompleted,
        refresherTriggered: false
      });
    });
  },
  onReady() {
    let userId = "" + app.globalData.userInfo.id;
    let that = this;
    that.setData({
      userId: userId,
      myAvatar: app.globalData.userInfo.avatar
    });
    let tim = app.$tim;
    let conversationID = this.data.conversationID;
    console.log("conversationID", conversationID);
    let promise = tim.getMessageList({
      conversationID: conversationID,
      count: 15
    });
    promise.then(function(imResponse) {
      const messageList = imResponse.data.messageList; // 消息列表。
      console.log("messageList", messageList);
      const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
      const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
      that.setData({
        messageList: messageList,
        nextReqMessageID: nextReqMessageID,
        isCompleted: isCompleted
      });
      that.scrollToBottom();
      // 将某会话下所有未读消息已读上报
      let promise2 = tim.setMessageRead({conversationID: conversationID});
      promise2.then(function(imResponse) {
        // 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
      }).catch(function(imError) {
        // 已读上报失败
        console.warn('setMessageRead error:', imError);
      });
    });

    tim.on(TIM.EVENT.MESSAGE_RECEIVED, function(event) {
      // 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
      // event.name - TIM.EVENT.MESSAGE_RECEIVED
      // event.data - 存储 Message 对象的数组 - [Message]
      console.log("MESSAGE_RECEIVED", event);
      let msgs = event.data;
      let messageList = that.data.messageList.concat(msgs);
      that.setData({
        messageList: messageList
      });
      that.scrollToBottom();
    });

    tim.on(TIM.EVENT.MESSAGE_REVOKED, function(event) {
      // 收到消息被撤回的通知
      // event.name - TIM.EVENT.MESSAGE_REVOKED
      // event.data - 存储 Message 对象的数组 - [Message] - 每个 Message 对象的 isRevoked 属性值为 true
    });

    tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, function(event) {
      // 收到会话列表更新通知，可通过遍历 event.data 获取会话列表数据并渲染到页面
      // event.name - TIM.EVENT.CONVERSATION_LIST_UPDATED
      // event.data - 存储 Conversation 对象的数组 - [Conversation]
    });

    tim.on(TIM.EVENT.GROUP_LIST_UPDATED, function(event) {
      // 收到群组列表更新通知，可通过遍历 event.data 获取群组列表数据并渲染到页面
      // event.name - TIM.EVENT.GROUP_LIST_UPDATED
      // event.data - 存储 Group 对象的数组 - [Group]
    });

    tim.on(TIM.EVENT.PROFILE_UPDATED, function(event) {
      // 收到自己或好友的资料变更通知
      // event.name - TIM.EVENT.PROFILE_UPDATED
      // event.data - 存储 Profile 对象的数组 - [Profile]
    });

    tim.on(TIM.EVENT.BLACKLIST_UPDATED, function(event) {
      // 收到黑名单列表更新通知
      // event.name - TIM.EVENT.BLACKLIST_UPDATED
      // event.data - 存储 userID 的数组 - [userID]
    });

    tim.on(TIM.EVENT.ERROR, function(event) {
      // 收到 SDK 发生错误通知，可以获取错误码和错误信息
      // event.name - TIM.EVENT.ERROR
      // event.data.code - 错误码
      // event.data.message - 错误信息
    });

    tim.on(TIM.EVENT.SDK_NOT_READY, function(event) {
      // 收到 SDK 进入 not ready 状态通知，此时 SDK 无法正常工作
      // event.name - TIM.EVENT.SDK_NOT_READY
    });

    tim.on(TIM.EVENT.KICKED_OUT, function(event) {
      // 收到被踢下线通知
      // event.name - TIM.EVENT.KICKED_OUT
      // event.data.type - 被踢下线的原因，例如:
      //    - TIM.TYPES.KICKED_OUT_MULT_ACCOUNT 多实例登录被踢
      //    - TIM.TYPES.KICKED_OUT_MULT_DEVICE 多终端登录被踢
      //    - TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED 签名过期被踢
    });
    // 拉取会话列表

    // tim.getConversationProfile();
  },
  /**
   * 组件的方法列表
   */
  methods: {},
  onLoad: function(options) {
    this.setData({
      conversationID: options.conversationID,
      formUserId: options.userID,
      formAvatar: options.avatar,
    });
    let that = this;
    let userId = that.data.formUserId;
    audio.handlerEvent( app.$tim,userId,this.data.canSend, function(message){
      console.log("cb msg",message);
      let msgs = that.data.messageList.concat([message]);
      that.setData({
        messageList: msgs,
        isFuncBarShow: false
      });
      that.scrollToBottom();
    });
  }
});
